'use client';

import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Input, Space, Modal, Form, message, Popconfirm, DatePicker, Select, Row, Col } from 'antd';
import { EditOutlined, DeleteOutlined, SearchOutlined, PlusOutlined, FilterOutlined, ReloadOutlined } from '@ant-design/icons';
import { getAnnouncement, uploadAnnouncement, updateAnnouncement, deleteAnnouncement, AnnouncementItem } from '@/lib/announcement';
import { getAllDepartments } from '@/lib/departments';
import Layout from '@/components/Layout';
import moment from 'moment';

const { TextArea } = Input;
const { Option } = Select;

// 部门类型选项
const DEPT_TYPES = [
  { value: 1, label: '职能部门' },
  { value: 2, label: '二级学院' },
  { value: 3, label: '教辅单位（其他部门）' }
];

// 定义表单值类型
interface AnnouncementFormValues {
  deptId: number;
  deptType: number;
  title: string;
  content: string;
  publishTime: moment.Moment;
}

// 定义部门类型
interface Department {
  deptId: number;
  deptName: string;
  [key: string]: any;
}

const AnnouncementManagementPage = () => {
  const [announcements, setAnnouncements] = useState<AnnouncementItem[]>([]);
  const [departments, setDepartments] = useState<Department[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm<AnnouncementFormValues>();
  const [editingAnnouncement, setEditingAnnouncement] = useState<AnnouncementItem | null>(null);
  const [searchText, setSearchText] = useState('');
  
  // 添加查询条件状态
  const [queryDeptType, setQueryDeptType] = useState<number | undefined>(undefined);
  const [queryDeptId, setQueryDeptId] = useState<number | undefined>(undefined);

  useEffect(() => {
    fetchAnnouncements();
    fetchDepartments();
  }, []);

  const fetchAnnouncements = async () => {
    setLoading(true);
    try {
      // 构建查询参数，只有在有值时才添加到查询参数中
      const params: { deptId?: number; deptType?: number } = {};
      if (queryDeptId !== undefined) {
        params.deptId = queryDeptId;
      }
      if (queryDeptType !== undefined) {
        params.deptType = queryDeptType;
      }
      
      console.log('【查询公告】请求参数:', params);
      const response = await getAnnouncement(params);
      console.log('【查询公告】响应结果:', response);
      
      if (response.code === 1) {
        setAnnouncements(response.data || []);
        if ((response.data || []).length === 0) {
          message.info('暂无公告数据');
        }
      } else if (response.code === 0) {
        // 没有公告的情况
        setAnnouncements([]);
        console.log('【查询公告】没有公告:', response.data);
        message.info(typeof response.data === 'string' ? response.data : '暂无公告');
      } else {
        throw new Error(response.msg || '获取公告失败');
      }
    } catch (error: any) {
      console.error('获取公告列表失败:', error);
      message.error('获取公告列表失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const fetchDepartments = async () => {
    try {
      console.log('【查询部门】请求参数:', {});
      const response = await getAllDepartments();
      console.log('【查询部门】响应结果:', response);
      
      if (response.data && response.data.code === 1) {
        setDepartments(response.data.data || []);
      }
    } catch (error: any) {
      message.error('获取部门列表失败: ' + (error.message || '未知错误'));
    }
  };

  // 添加重置查询条件的函数
  const handleResetQuery = () => {
    setQueryDeptType(undefined);
    setQueryDeptId(undefined);
    setSearchText('');
    // 重置后重新查询
    setTimeout(() => {
      fetchAnnouncements();
    }, 0);
  };

  // 添加执行查询的函数
  const handleQuery = () => {
    fetchAnnouncements();
  };

  const showModal = (record: AnnouncementItem | null = null) => {
    setEditingAnnouncement(record);
    if (record) {
      form.setFieldsValue({
        deptId: record.deptId,
        deptType: record.deptType || 1, // 默认为职能部门
        title: record.title,
        content: record.content,
        publishTime: moment(record.publishTime)
      });
    } else {
      form.resetFields();
      // 设置默认发布时间为当前时间
      form.setFieldsValue({
        publishTime: moment()
      });
    }
    setModalVisible(true);
  };

  const handleModalOk = () => {
    form.validateFields().then(values => {
      if (editingAnnouncement) {
        handleEditAnnouncement(values);
      } else {
        handleAddAnnouncement(values);
      }
    });
  };

  const handleAddAnnouncement = async (values: AnnouncementFormValues) => {
    try {
      if (!values.deptId) {
        throw new Error('请选择部门');
      }

      if (!values.deptType) {
        throw new Error('请选择部门类型');
      }

      const requestData = {
        deptId: values.deptId,
        deptType: values.deptType,
        title: values.title,
        content: values.content,
        publishTime: values.publishTime.format('YYYY-MM-DDTHH:mm:ss')
      };
      
      console.log('【添加公告】请求参数:', requestData);
      const response = await uploadAnnouncement(requestData);
      console.log('【添加公告】响应结果:', response.data);
      
      if (response.data && response.data.code === 1) {
        message.success('添加公告成功');
        setModalVisible(false);
        fetchAnnouncements();
      } else {
        throw new Error((response.data && response.data.msg) || '添加失败');
      }
    } catch (error: any) {
      console.error('添加公告失败:', error);
      message.error('添加公告失败: ' + (error.message || '未知错误'));
    }
  };

  const handleEditAnnouncement = async (values: AnnouncementFormValues) => {
    try {
      if (!editingAnnouncement) {
        throw new Error('编辑的公告不存在');
      }
      
      if (!values.deptType) {
        throw new Error('请选择部门类型');
      }

      const requestData = {
        id: editingAnnouncement.id,
        deptId: values.deptId,
        deptType: values.deptType,
        title: values.title,
        content: values.content,
        publishTime: values.publishTime ? values.publishTime.format('YYYY-MM-DDTHH:mm:ss') : undefined
      };
      
      console.log('【更新公告】请求参数:', requestData);
      const response = await updateAnnouncement(requestData);
      console.log('【更新公告】响应结果:', response.data);
      
      if (response.data && response.data.code === 1) {
        message.success('更新公告成功');
        setModalVisible(false);
        fetchAnnouncements();
      } else {
        throw new Error((response.data && response.data.msg) || '更新失败');
      }
    } catch (error: any) {
      console.error('更新公告失败:', error);
      message.error('更新公告失败: ' + (error.message || '未知错误'));
    }
  };

  const handleDelete = async (id: number) => {
    try {
      console.log('【删除公告】请求参数:', { id });
      const response = await deleteAnnouncement(id.toString());
      console.log('【删除公告】响应结果:', response.data);
      
      if (response.data && response.data.code === 1) {
        message.success('删除公告成功');
        fetchAnnouncements();
      } else {
        throw new Error((response.data && response.data.msg) || '删除失败');
      }
    } catch (error: any) {
      console.error('删除公告失败:', error);
      message.error('删除公告失败: ' + (error.message || '未知错误'));
    }
  };

  const columns = [
    { title: '标题', dataIndex: 'title', key: 'title' },
    { 
      title: '部门', 
      dataIndex: 'deptName', 
      key: 'deptName',
    },
    { 
      title: '部门类型', 
      dataIndex: 'deptType', 
      key: 'deptType',
      render: (type: number) => {
        const deptType = DEPT_TYPES.find(t => t.value === type);
        return deptType ? deptType.label : '未知类型';
      }
    },
    { 
      title: '内容', 
      dataIndex: 'content', 
      key: 'content', 
      ellipsis: true,
      width: '30%'
    },
    { 
      title: '发布时间', 
      dataIndex: 'publishTime', 
      key: 'publishTime',
      render: (text: string) => moment(text).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: AnnouncementItem) => (
        <Space size="middle">
          <Button 
            icon={<EditOutlined />} 
            onClick={() => showModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个公告吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              icon={<DeleteOutlined />} 
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const filteredAnnouncements = announcements.filter(
    announcement => announcement.title.toLowerCase().includes(searchText.toLowerCase()) ||
                    announcement.content.toLowerCase().includes(searchText.toLowerCase())
  );

  // 添加查询表单组件
  const renderQueryForm = () => (
    <Card style={{ marginBottom: 16 }}>
      <Row gutter={16}>
        <Col xs={24} sm={12} md={6} lg={6}>
          <Form.Item label="部门类型" style={{ marginBottom: 0 }}>
            <Select
              placeholder="选择部门类型"
              style={{ width: '100%' }}
              allowClear
              value={queryDeptType}
              onChange={(value) => setQueryDeptType(value)}
            >
              {DEPT_TYPES.map(type => (
                <Option key={type.value} value={type.value}>{type.label}</Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
        <Col xs={24} sm={12} md={6} lg={6}>
          <Form.Item label="部门" style={{ marginBottom: 0 }}>
            <Select
              placeholder="选择部门"
              style={{ width: '100%' }}
              allowClear
              value={queryDeptId}
              onChange={(value) => setQueryDeptId(value)}
              showSearch
              optionFilterProp="children"
            >
              {departments.map(dept => (
                <Option key={dept.deptId} value={dept.deptId}>{dept.deptName}</Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
        <Col xs={24} sm={12} md={6} lg={6}>
          <Form.Item label="关键字" style={{ marginBottom: 0 }}>
            <Input
              placeholder="搜索公告标题或内容"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              prefix={<SearchOutlined />}
              allowClear
            />
          </Form.Item>
        </Col>
        <Col xs={24} sm={12} md={6} lg={6} style={{ textAlign: 'right', display: 'flex', alignItems: 'flex-end', justifyContent: 'flex-end' }}>
          <Button 
            type="primary" 
            icon={<FilterOutlined />} 
            onClick={handleQuery}
            style={{ marginRight: 8 }}
          >
            查询
          </Button>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleResetQuery}
          >
            重置
          </Button>
        </Col>
      </Row>
    </Card>
  );

  return (
    <Layout>
      <Card title="公告管理">
        {renderQueryForm()}
        <div style={{ marginBottom: 16, textAlign: 'right' }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => showModal()}>
            添加公告
          </Button>
        </div>
        <Table
          columns={columns}
          dataSource={filteredAnnouncements}
          rowKey="id"
          loading={loading}
        />
      </Card>

      <Modal
        title={editingAnnouncement ? "编辑公告" : "添加公告"}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入标题' }]}>
            <Input />
          </Form.Item>
          <Form.Item 
            name="deptId" 
            label="部门" 
            rules={[{ required: true, message: '请选择部门' }]}
          >
            <Select placeholder="请选择部门">
              {departments.map(dept => (
                <Option key={dept.deptId} value={dept.deptId}>{dept.deptName}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item 
            name="deptType" 
            label="部门类型" 
            rules={[{ required: true, message: '请选择部门类型' }]}
          >
            <Select placeholder="请选择部门类型">
              {DEPT_TYPES.map(type => (
                <Option key={type.value} value={type.value}>{type.label}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="content" label="内容" rules={[{ required: true, message: '请输入内容' }]}>
            <TextArea rows={4} />
          </Form.Item>
          <Form.Item name="publishTime" label="发布时间" rules={[{ required: true, message: '请选择发布时间' }]}>
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default AnnouncementManagementPage;